<template>
  <div>
    <div class="f">
      <el-button type="primary" @click="redactFn(1)">添加角色</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <div
              :key="item.id"
              v-for="item in props.row.children"
              style="width: 100%"
            >
              <div class="f1 r">
                <el-tag
                  closable
                  :disable-transitions="false"
                  @close="handleCloses(item, props.row.children, props.row.id)"
                >
                  {{ item.authName }}
                </el-tag>
                <div>
                  <div
                    :key="items.id"
                    v-for="items in item.children"
                    class="f1 r"
                  >
                    <el-tag
                      closable
                      :disable-transitions="false"
                      @close="handleCloses(items, item.children, props.row.id)"
                      type="success"
                    >
                      {{ items.authName }}
                    </el-tag>
                    <div class="f1 r war">
                      <div
                        :key="itemss.id"
                        v-for="itemss in items.children"
                        class="f1 r war"
                      >
                        <el-tag
                          closable
                          :disable-transitions="false"
                          type="warning"
                          @close="
                            handleCloses(itemss, items.children, props.row.id)
                          "
                        >
                          <!-- @click="deleteRigthtsR(props.row.id, itemss.id)" -->
                          {{ itemss.authName }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="index"> </el-table-column>
      <el-table-column label="角色名" prop="id"> </el-table-column>
      <el-table-column label="商品名称" prop="roleName"> </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <div class="f">
            <el-button type="primary" @click="redactFn(0, scope.row.id)"
              >编辑</el-button
            >
            <el-button type="danger" @click="removeFn(scope.row.id)"
              >删除</el-button
            >
            <el-button type="success" @click="init(scope.row)"
              >分配权限</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- INFO添加或修改对话框 -->
    <el-dialog
      :title="dialogVisibleIndex == 0 ? '修改角色' : '添加角色'"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form :model="form" ref="forms" :rules="rules">
        <el-form-item
          label="角色名"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>

        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('forms')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- INFO树状图修改对话框 -->

    <el-dialog
      title="分配权限"
      @click="dialogTableVisible = true"
      :visible.sync="dialogTableVisible"
    >
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-expanded-keys="[2, 3]"
        :default-checked-keys="defaultList"
        :props="defaultProps"
        default-expand-all
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="getCheckedNodes()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import permissions from "@/api/permissions";
export default {
  name: "RolesFrom",
  props: ["tableData", "getRights"],
  data() {
    return {
      dialogVisible: false,
      dialogTableVisible: false,
      dialogVisibleIndex: 0,
      id: "",
      form: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "change" },
        ],
      },
      formLabelWidth: "120px",
      data: [
        {
          id: 1,
          label: "一级 1",
          children: [
            {
              id: 4,
              label: "二级 1-1",
              children: [
                {
                  id: 9,
                  label: "三级 1-1-1",
                },
                {
                  id: 10,
                  label: "三级 1-1-2",
                },
              ],
            },
          ],
        },
        {
          id: 2,
          label: "一级 2",
          children: [
            {
              id: 5,
              label: "二级 2-1",
            },
            {
              id: 6,
              label: "二级 2-2",
            },
          ],
        },
        {
          id: 3,
          label: "一级 3",
          children: [
            {
              id: 7,
              label: "二级 3-1",
            },
            {
              id: 8,
              label: "二级 3-2",
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      defaultList: [],
    };
  },
  methods: {
    handleCloses(tag, list, id) {
      this.$confirm("确认关闭？")
        .then(() => {
          list.splice(list.indexOf(tag), 1);
          this.deleteRigthtsR(id, tag.id);
        })
        .catch(() => {});
    },
    async deleteRigthtsR(id, itemId) {
      await permissions.deleteRolesRights(id, itemId);
    },
    async init(val) {
      let res = await permissions.getTree();
      this.data = res;
      this.id = val.id;
      this.dialogTableVisible = true;
      let arr = [];
      val.children.forEach((item) => {
        item.children.forEach((items) => {
          items.children.forEach((i) => {
            arr.push(i.id);
          });
        });
      });
      this.defaultList = arr;
    },
    // 分配权限
    async getCheckedNodes() {
      let a = this.$refs.tree.getCheckedNodes();
      let res = this.$refs.tree.getCheckedKeys();
      // console.log(this.$refs.tree.getCheckedNodes());
      // let arr = [];
      a.forEach((item) => {
        if (typeof item.pid != "number") {
          let b = item.pid.split(",");
          b.forEach((item) => {
            if (res.indexOf(item * 1) == -1) {
              res.push(item * 1);
            }
          });
          // arr = arr.concat(item.pid.split(","));
        }
      });
      // let res1 = [...new Set(arr)];
      // res1 = res1.map((item) => item * 1);
      // res = [...new Set(res.concat(res1))];
      let aaa = { rids: res.join(",") };
      await permissions.postRigthtsRights(this.id, aaa);
      this.getRights();
      this.dialogTableVisible = false;
    },
    // 验证 并且进行修改和添加数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogVisibleIndex) {
            //  添加数据
            permissions.postRigthtsRoles(this.form).then(() => {
              this.getRights();
            });
          } else {
            // 修改
            permissions
              .putRigthtsRoles(this.form.roleId, this.form)
              .then(() => {
                this.getRights();
              });
          }
          this.dialogVisible = false;
          this.$refs[formName].resetFields();
        } else {
          return false;
        }
      });
    },
    // 判断是修改还是添加
    redactFn(index, id) {
      this.dialogVisibleIndex = index;
      if (id) {
        permissions.getRigthtsRoles(id).then((res) => {
          this.form = res;
          this.dialogVisible = true;
        });
      } else {
        this.dialogVisible = true;
      }
      if (index != 0) {
        this.form = {
          roleName: "",
          roleDesc: "",
        };
      }
    },
    //删除
    async removeFn(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          permissions.deleteRigthtsRoles(id).then(() => {
            this.getRights();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 是否关闭
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
  },
  created() {
    // this.init();
  },
};
</script>

<style lang="scss" scoped>
.f {
  display: flex;
}
.f1 {
  display: flex;
  align-items: center;
}
.war {
  flex-wrap: wrap;
}
.r {
  margin: 10px;
}
.el-icon-caret-right {
  font-family: element-icons !important;
  font-style: normal;
  font-weight: 400;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  vertical-align: baseline;
  display: inline-block;
  -webkit-font-smoothing: antialiased;
}
.el-icon-caret-right:before {
  content: "\e791";
}
</style>